<template>
  <div :style="{display:!openCheck?'flex':''}"
       style="justify-content: space-between;margin: 0 auto;margin-top: 15px;width: 100%">
    <div :style="{width:openCheck ?'100%':'30%'}">
      <basic-container>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>广告主名称</span>
          </div>
          <div class="clearfix">
            <el-row>
              <el-col :span="24">
                <div class="grid-content bg-purple-light">{{(advData[0].advName)}}</div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </basic-container>
    </div>
    <div :style="{width:openCheck?'100%':'70%'}">
      <basic-container>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>账户列表</span>
          </div>
          <div class="clearfix">
            <avue-crud :option="accountOption"
                       :data="accountListData"
                       :table-loading="accountLoading"
                       ref="crudAccount"
                       @on-load="onloadAccount"
                       :row-class-name="getRowClassName"
                       share2advAcctTable
            >
              <template slot="permission" slot-scope="scope">
                <el-select id="id-business-components-offershaare-accountPermissionChange"
                           :disabled="!(!openCheck && scope.row.id != null)" v-model="scope.row.permission"
                           @change="accountPermissionChange($event,scope.row)">
                  <el-option v-for="item in accountPermissionList" :key="item.dictKey*1"
                             :label="item.dictValue" :value="item.dictKey*1">
                  </el-option>
                </el-select>
              </template>
              <template slot="menuLeft">
                <el-button
                  :disabled="offerInfo === null"
                  type="primary"
                  size="small"
                  icon="el-icon-plus"
                  plain
                  @click="handleAccountAdd"
                  v-if="!openCheck"
                >新 增
                </el-button>
              </template>
              <template slot="menu" slot-scope="{row}">
                <el-button
                  id="id-business-components-offershaare-deleteAccount"
                  :disabled="row.id == null"
                  type="primary"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteAccount(row)"
                >删除
                </el-button>
              </template>
            </avue-crud>
          </div>
          <div style="text-align: right;">
            <el-button id="id-business-components-offershaare-confirmShare2adv" @click="confirmShare2adv" type="primary" size="mini" v-if="advNotarize">确认分享</el-button>
          </div>
        </el-card>
      </basic-container>
    </div>
    <!--    account新增dialog-->
    <el-dialog :visible.sync="accountAddDialog" :modal-append-to-body="false" width="70%"
               :before-close="accountAddDialogClose">
      <offer-share2adv-account-add ref="idleAccountAdd" :offer-id="offerId"></offer-share2adv-account-add>
      <span slot="footer" class="dialog-footer">
        <el-button id="id-business-components-offershaare-accountAddDialogClose" @click="accountAddDialogClose">取 消</el-button>
        <el-button id="id-business-components-offershaare-submitAccount" type="primary" @click="submitAccount">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import offerShare2advAccountAdd from './offerShare2advAccountAdd'
  import {getSysDictList} from '@/api/system/dict'
  import {
    getShare2advAccount,
    removeShare2advAccount,
    confirmShare2advAccount,
    updateShare2advAccountPermission
  } from '@/api/business/share'
  import {getDetail as getAdvDetail} from '@/api/business/customer'
  import { getExternalAccount } from "@/api/business/account";

  export default {
    name: 'offerShareAdv',
    components: {
      offerShare2advAccountAdd,
    },
    props: {
      confirmToShare: {
        type: Number
      },
      offerId: {
        type: String
      },
      offerInfo: {
        type: Object
      },
      openCheck: {
        type: String
      },
    },
    watch: {
      offerInfo: {
        deep: true,
        handler(val, old) {
          if (val === old) {
            return
          }
          this.loadAdvData();
        }
      },
      offerId: {
        deep: true,
        handler(val, old) {
          if (val === old) {
            return
          }
          getSysDictList("account_offer_permission").then(map => {
            this.accountPermissionList = map['account_offer_permission']
          })
          getExternalAccount(this.offerId).then(res => {
            this.accountData = res.data.data;
            this.updateNewAccountData();
          })
        }
      },
    },
    data() {
      return {
        advNotarize: true,
        advData: [{advName: ''}],
        //账户列表配置
        accountOption: {
          editBtn: false,
          addBtn: false,
          delBtn:false,
          refreshBtn: false,
          columnBtn: false,
          menuWidth: 120,
          menu: true,
          column: [
            {
              label: '账户名称',
              prop: 'name',
              width: 300,
            }, {
              label: '账户ID',
              prop: 'platformId',
              width: 250,
            }, {
              label: '权限',
              prop: 'permission',
              slot: true,
              width: 300,
            }
          ]
        },
        originAccountListData: [],
        accountListData: [],//账户数据
        accountLoading: false,
        accountPermissionList: [],//账户列表权限
        accountAddDialog: false,//account新增弹窗
        pageAccount: {
          pageSize: 10,
          pageSizes: [10, 30, 50, 100, 200],
          currentPage: 1,
          total: 0
        },
        accountData: [],
        newAccountData: [],
      }
    },
    created() {
      if (this.confirmToShare === 1){
        this.advNotarize = false
        this.accountOption.menu = false
      }
    },
    methods: {
      getDictValue(list, key) {
        if (!key || !list || list.length == 0) {
          return key;
        }
        let val = [];
        let newkeys = key;
        if (!(key instanceof Array)) {
          newkeys = [key];
        }
        newkeys.forEach((item) => {
          if (item) {
            for (let i = 0; i < list.length; i++) {
              if (list[i].dictKey == item) {
                val.push(list[i].dictValue);
                return;
              }
            }
          }
        });
        return newkeys.join(",");
      },
      updateNewAccountData() {
        let newAccountData = [];
        this.accountData.forEach((ele)=>{
          let newEle = {
            name: ele.name,
            platform: ele.platform,
            platformId: ele.platformId,
            permission: ((ele.permission == -1)?null:ele.permission),
          };
          newAccountData.push(newEle);
        });
        this.newAccountData = newAccountData;
        this.updateAccountListData();
      },
      updateAccountListData() {
        this.accountListData = this.newAccountData.concat(this.originAccountListData);
      },
      getRowClassName(item) {
        if(item.row.id == undefined) {
          return "externalAcctClass";
        } else {
          return "";
        }
      },
      loadAdvData() {
        let self = this;
        if (self.offerInfo != null && (self.offerInfo.customerId) && self.offerInfo.customerId != -1) {
          getAdvDetail(self.offerInfo.customerId).then(res => {
            if (res.data.code === 200) {
              self.advData = [{advName: res.data.data.name}];
            }
          });
          self.onloadAccount(self.pageAccount, {});
        }
      },
      onloadAccount(page, params = {}) {
        let self = this;
        self.accountLoading = true;
        if (!self.offerId) {
          self.accountLoading = false;
          self.pageAccount.total = 0;
          self.originAccountListData = [];
          self.accountData = [];
          self.updateNewAccountData();
          self.updateAccountListData();
          return
        }
        let param = {
          type: 'shareable',
          offerId: self.offerId,
        };
        getShare2advAccount(
          page.currentPage,
          page.pageSize,
          Object.assign(params, param)
        ).then(res => {
          const data = res.data.data
          self.pageAccount.total = data.total;
          data.records.map(item => {
            if (item.permission == -1) {
              item.permission = null;
            }
          });
          self.originAccountListData = data.records;
          self.updateAccountListData();
          self.accountLoading = false;
        })
      },
      //修改账户列表权限
      accountPermissionChange(event, row) {
        updateShare2advAccountPermission({offerId: this.offerId, accountId: row.accountId, permission: row.permission});
      },
      //account列表点击删除
      deleteAccount(row) {
        if(row.id == undefined) {
          return;
        }
        removeShare2advAccount(this.offerId, row.id).then(res => {
          if (res.data.code == 200) {
            this.$message({type: 'success', message: '删除成功'})
            this.onloadAccount(this.pageAccount, {})
          }
        })
      },
      // account新增
      handleAccountAdd() {
        let self = this;
        let excludeIds = [];
        for (let i = 0; i < self.accountListData.length; i++) {
          if(self.accountListData[i].accountId == undefined) {
            continue;
          }
          excludeIds[i] = self.accountListData[i].accountId;
        }
        self.excludeAcctIds = excludeIds;
        self.accountAddDialog = true;
        setTimeout(() => {
          self.$refs.idleAccountAdd.onLoad(self.$refs.idleAccountAdd.page)
        }, 50);
      },
      //账户页面关闭
      accountAddDialogClose() {
        this.accountAddDialog = false
        this.$refs.idleAccountAdd.$refs.crud.searchReset();
      },
      submitAccount() {
        this.$refs.idleAccountAdd.submitAccountAdd()
        this.accountAddDialogClose()
      },
      confirmShare2adv() {
        let self = this;
        confirmShare2advAccount({offerId: self.offerId}).then(res => {
          if (res.data.code == 200) {
            self.$message({type: 'success', message: '分享成功'})
            self.onloadAccount(self.pageAccount, {})
          }
        });
      }
    }
  }
</script>
<style scoped>
  /deep/[share2advAcctTable] tr.externalAcctClass {
    background: lightgray;
  }
</style>
